package com.flycms.modules.links.tags;

import com.flycms.common.pager.Pager;
import com.flycms.common.utils.StringUtils;
import com.flycms.initialize.TagsPlugin;
import com.flycms.modules.links.entity.Links;
import com.flycms.modules.links.service.LinksService;
import com.flycms.modules.site.entity.Site;
import com.flycms.modules.site.service.SiteService;
import com.flycms.modules.system.service.ConfigureService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * 资讯列表标签
 *
 * @author sunkaifei
 * 
 */
@Service
public class Linkslist extends TagsPlugin {
	@Autowired
	private SiteService siteService;
	@Autowired
	private LinksService linksService;
	@Autowired
	private ConfigureService systemService;
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
		try {
			// 获取页面的参数
			//用户id
			Long siteId = null;
			//用户id
			int typeid = 0;

			String sort=null;

			String order=null;
			//当前页数
			int p = 1;
			//每页记录数
			int rows = 10;

			HttpServletRequest httpRequest=(HttpServletRequest)request;
			String domainString=StringUtils.twoStageDomain(httpRequest.getRequestURL().toString());
			if (!org.springframework.util.StringUtils.isEmpty(domainString)) {
				siteId = siteService.findSiteByDomain(domainString);
			}else{
				Site site =siteService.findById(Long.parseLong(systemService.findByKeyCode("default_site")));
				siteId = site.getId();
			}
			//处理标签变量
			Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
			for(String str:paramWrap.keySet()){
				if("typeid".equals(str)){
					typeid = Integer.parseInt(paramWrap.get(str).toString());
				}
				if("sort".equals(str)){
					sort = paramWrap.get(str).toString();
				}
				if("order".equals(str)){
					order = paramWrap.get(str).toString();
				}
				if("p".equals(str)){
					p = Integer.parseInt(paramWrap.get(str).toString());
				}
				if("rows".equals(str)){
					rows = Integer.parseInt(paramWrap.get(str).toString());
				}
			}

			Pager<Links> pageVo = linksService.queryLinksPager(siteId,typeid, p, rows, sort, order);
			env.setVariable("list", builder.build().wrap(pageVo));
		} catch (Exception e) {
			env.setVariable("list", builder.build().wrap(null));
		}
		body.render(env.getOut());
	}
}
